package br.com.simtecnologia.util;

import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class ManyToOneMap<M,O,V> implements Serializable {
	
	private static final long serialVersionUID = 5542563273902409090L;
	private Map<M, Pair<O, V>> map1 = new HashMap<M, Pair<O, V>>();
	private Map<O, Pair<Set<M>, V>> map2 = new HashMap<O, Pair<Set<M>, V>>();
	
	public void put(M key1, O key2, V value) {
		map1.put(key1, new Pair<O, V>(key2, value));
		Pair<Set<M>, V> old = map2.get(key2);
		Set<M> set = (old == null) ? new HashSet<M>() : old.getFirst();
		map2.put(key2, new Pair<Set<M>, V>(set, value));
		set.add(key1);
	}
	
	public boolean containsMany(M kayMany) {
		return map1.containsKey(kayMany);
	}
	
	public boolean containsOne(O keyOne) {
		return map2.containsKey(keyOne);
	}
	
	public boolean containsValue(V value) {
		return map1.containsValue(value);
	}
	
	public Pair<O, V> getPairOne(M keyMany) {
		return map1.get(keyMany);
	}
	
	public Pair<Set<M>, V> getPairMany(O oneKey) {
		return map2.get(oneKey);
	}
	
	public Pair<O,V> removeMany(M key) {
		Pair<O, V> result = map1.remove(key);
		
		if (result != null) {
			removeOne(result.getFirst());
		}
		return result;
	}
	
	public Pair<Set<M>,V> removeOne(O key) {
		Pair<Set<M>, V> result = map2.remove(key);		
		if (result != null) {
			for(M m : result.getFirst())
				map1.remove(m);
			
			map1.remove(result.getFirst());
		}
		return result;
	}
	
	public void clear() {
		map1.clear();
		map2.clear();
	}
}
